package cn.kazuz.service.login.controller;

import cn.kazuz.common.util.annotation.Authorization;
import cn.kazuz.common.util.result.Result;
import cn.kazuz.service.login.entity.AdminLogin;
import cn.kazuz.service.login.entity.dto.AdminLoginDto;
import cn.kazuz.service.login.entity.vo.AdminLoginVo;
import cn.kazuz.service.login.service.AdminLoginService;
import cn.kazuz.service.login.utils.JwtUtils;
import lombok.NonNull;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author kazu
 * @Date 2023/09/24 23:02
 * @Version 1.0
 */
@SuppressWarnings({"all"})
@RestController
@RequestMapping("admin_login")
@CrossOrigin
public class AdminLoginController {

	@Autowired
	private AdminLoginService adminLoginService;

	/**
	 * 管理员登录
	 *
	 * @param adminLoginDto
	 * @return
	 */
	@PostMapping("login")
	public Result login(@RequestBody @NonNull AdminLoginDto adminLoginDto,
	                    HttpServletRequest request, HttpServletResponse response) throws LoginException {
		if (adminLoginDto.getUsername() == null || adminLoginDto.getPassword() == null) {
			LoginException loginException = new LoginException("请求登录异常");
			loginException.printStackTrace();
			return Result.error().message(loginException.getMessage());
		} else {
			AdminLogin adminLogin = adminLoginService.login(adminLoginDto.getUsername(), adminLoginDto.getPassword());
			if (adminLogin == null) {
				LoginException loginException = new LoginException("用户名或密码错误，请检查正确后重试");
				loginException.printStackTrace();
				return Result.error().message(loginException.getMessage());
			} else {
				AdminLoginVo adminLoginVo = new AdminLoginVo();
				String token = JwtUtils.getToken(adminLogin);
				BeanUtils.copyProperties(adminLogin, adminLoginVo);
				response.setHeader("Authorization", token);
				return Result.ok().data("adminId", adminLoginVo.getAdminId())
						.data("adminUsername", adminLoginVo.getAdminUsername())
						.data("adminPassword", adminLoginVo.getAdminPassword())
						.data("adminPhone", adminLoginVo.getAdminPhone())
						.data("createTime", adminLoginVo.getCreateTime())
						.data("modifyTime", adminLoginVo.getModifyTime())
						.data("adminAvatar", adminLoginVo.getAdminAvatar())
						.data("token", token);
			}
		}
	}

}
